﻿using Abp.Application.Services.Dto;
using Abp.Extensions;
using Abp.Linq.Extensions;
using DHJ.Cost.ManHours.Dto;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Task = System.Threading.Tasks.Task;

namespace DHJ.Cost.ManHours
{
    public class ManHourAppService : CostAppServiceBase, IManHourAppService
    {
        private readonly IManHourManager _manHourManager;

        public ManHourAppService(IManHourManager manHourManager)
        {
            _manHourManager = manHourManager;
        }

        public async Task<PagedResultDto<BatchManHourListDto>> GetBatchManHours(GetBatchManHoursInput input)
        {
            var query = _manHourManager.ManHours
                .Include(mh => mh.Batch).ThenInclude(b=>b.Task)
                .Where(mh => mh.Time.Year == input.Year && mh.Time.Month == input.Month)
                .WhereIf(input.Workshop.HasValue, mh => mh.Workshop == input.Workshop.Value)
                .WhereIf(!input.Filter.IsNullOrWhiteSpace(), e =>
                        e.BatchId.Contains(input.Filter) ||
                        e.Batch.Task.ProductId.Contains(input.Filter) ||
                        e.Batch.Task.TaskNum.Contains(input.Filter) ||
                        e.Batch.Task.ProductName.Contains(input.Filter));

            var count = await query.CountAsync();

            var manHours = await query
                .OrderBy(input.Sorting)
                .PageBy(input)
                .ToListAsync();

            return new PagedResultDto<BatchManHourListDto>(count, ObjectMapper.Map<List<BatchManHourListDto>>(manHours));
        }
    }
}